package com.cl.mypureframe.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cl.mypureframe.R;
import com.cl.mypureframe.model.PhotoMod;
import com.cl.mypureframe.util.FileSizeUtil;
import com.cl.mypureframe.util.GLobalConstant;
import com.cl.mypureframe.util.GlideEngine;
import com.cl.mypureframe.util.ImageUtils;
import com.cl.mypureframe.util.Log;
import com.cl.mypureframe.util.PhotoZoomGlideEngine;
import com.cl.mypureframe.util.Utils;
import com.cl.photozoom.PhotoZoomInstance;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Class: PictureSelecorActivity
 * @Description:
 * @Author: ChenLei
 * @Date: 2020/12/7---13:54
 */
public class PictureSelectorActivity extends BasePicActivity {
    private static final int MAX_PICNUM = 9;
    private ArrayList<PhotoMod> picList;// 选中图片实体类的集合，gridview用
    private List<LocalMedia> resultList;
    private BaseQuickAdapter<PhotoMod, BaseViewHolder> gridAdapter;
    private PhotoMod selPhotoMod;
    private TextView tvTab1, tvTab2, tvTab3;
    private GridLayoutManager gridLayoutManager;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private RecyclerView rv_grid;
    private ExecutorService singleThreadExecutor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initContenViewAndBack(R.layout.activity_picture, R.string.picactivity);

        picList = new ArrayList<>();
        resultList = new ArrayList<>();
        tvTab1 = findViewById(R.id.tv_tab1);
        tvTab2 = findViewById(R.id.tv_tab2);
        tvTab3 = findViewById(R.id.tv_tab3);

        rv_grid = findViewById(R.id.rv_grid);
        gridAdapter = new BaseQuickAdapter<PhotoMod, BaseViewHolder>(R.layout.item_uphoto) {
            @Override
            protected void convert(@NonNull BaseViewHolder helper, PhotoMod item) {
                helper.setGone(R.id.iv_del, item.type == PhotoMod.TYPE_ADD || item.type == PhotoMod.TYPE_NORPIC);

                ImageView ivTab = helper.getView(R.id.iv_tab);
                if (item.type == PhotoMod.TYPE_ADD) {
                    ivTab.setImageResource(R.mipmap.ic_add_image);
                } else {
                    ImageUtils.glideLoader(aContext, item.picurl, ivTab);
//                    Glide.with(aContext).load(item.picurl).placeholder(R.mipmap.zwt)
//                            .skipMemoryCache(true)// 跳过内存缓存
//                            .diskCacheStrategy(DiskCacheStrategy.NONE)// 不缓冲disk硬盘中
//                            .into(ivTab);
                    ivTab.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            item.randomHeight > 0 ? item.randomHeight : Utils.dip2px(aContext, 100)));
                }
            }
        };
        rv_grid.setAdapter(gridAdapter);
        gridLayoutManager = new GridLayoutManager(this, 3);
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        gridAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                selPhotoMod = (PhotoMod) adapter.getItem(position);
                if (selPhotoMod.type == PhotoMod.TYPE_ADD) {
//                    showPop();// 选择图片
//                    showPictureSelector();
                    recordVideo();
                } else {
                    showPreview(position);
                }
            }
        });

        gridAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                // 点叉叉删除操作
                PhotoMod photoMod = (PhotoMod) adapter.getItem(position);
                resultList.remove(position);
                picList.remove(photoMod);
                if (picList.get(picList.size() - 1).type == PhotoMod.TYPE_NORMAL) {
                    picList.add(PhotoMod.initData());
                }
                gridAdapter.notifyDataSetChanged();
            }
        });
        gridAdapter.addChildClickViewIds(R.id.iv_del);
        gridAdapter.setNewInstance(picList);

        // 1. 创建单线程化线程池
        singleThreadExecutor = Executors.newSingleThreadExecutor();

        onButtonClick(findViewById(R.id.tv_tab1));
    }

    // 多图选择
    private void showPictureSelector() {
        PictureSelector.create(PictureSelectorActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .isCompress(true)
                .compressQuality(50)
                .compressSavePath(GLobalConstant.PHOTO_PATH)
//                .selectionMode(PictureConfig.MULTIPLE)
//                .isEnableCrop(true)
//                .showCropFrame(false)
//                .showCropGrid(false)
//                .rotateEnabled(false)
//                .circleDimmedLayer(true)
                .selectionData(resultList)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // 结果回调
                        int size = result.size();
                        if (size > 0) {
                            resultList = result;
                            picList.clear();
                            for (LocalMedia localMedia : result) {
//                                picList.add(new PhotoMod(localMedia.getRealPath()));
                                picList.add(new PhotoMod(localMedia.getCompressPath()));
                                Log.i(TAG, "File size", localMedia.getRealPath() + ":" + FileSizeUtil.getAutoFileOrFilesSize(localMedia.getRealPath()));
                                Log.w(TAG, "File size", localMedia.getCompressPath() + ":" + FileSizeUtil.getAutoFileOrFilesSize(localMedia.getCompressPath()));
                            }
                            // 不足最大数量，最后一个显示加号
                            if (size < MAX_PICNUM) {
                                picList.add(PhotoMod.initData());
                            }
                            gridAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onCancel() {
                        // 取消
                    }
                });
    }

    // 拍摄视频
    private void recordVideo() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofVideo())
                .imageEngine(GlideEngine.createGlideEngine())
                .recordVideoSecond(30)
                .videoQuality(0)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        // 结果回调
                        for (LocalMedia localMedia : result) {
                            Log.i(TAG, "recordVideo:File size", localMedia.getRealPath() + ":" + FileSizeUtil.getAutoFileOrFilesSize(localMedia.getRealPath()));
                        }
                    }

                    @Override
                    public void onCancel() {
                        // 取消
                    }
                });
    }

    // 预览图片
    private void showPreview(int position) {
//        PictureSelector.create(this)
//                .themeStyle(R.style.picture_default_style) // xml设置主题
//                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
//                .isNotPreviewDownload(true)
//                .openExternalPreview(position, resultList);
        PhotoZoomInstance.create(this)
                .setImageEngine(PhotoZoomGlideEngine.createGlideEngine())
//                .isShowDownload(true)
//                .setSavePath(GLobalConstant.PHOTO_PATH)
                .openPreview(position, picList);
    }

    @Override
    protected void getFilePath(String filePath) {
        selPhotoMod.picurl = filePath;
        selPhotoMod.type = PhotoMod.TYPE_NORMAL;

        // 不足最大数量，最后一个显示加号
        if (picList.size() < MAX_PICNUM) {
            picList.add(PhotoMod.initData());
        }
        gridAdapter.notifyDataSetChanged();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {

            }
        };
        singleThreadExecutor.execute(runnable);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onButtonClick(View view) {
        picList.clear();
        resultList.clear();
        switch (view.getId()) {
            case R.id.tv_tab1:
                onTextColor(tvTab1);
                rv_grid.setLayoutManager(gridLayoutManager);
                picList.add(PhotoMod.initData());
                break;
            case R.id.tv_tab2:
                onTextColor(tvTab2);
                rv_grid.setLayoutManager(gridLayoutManager);
                picList.addAll(PhotoMod.initGridData());
                for (int i = 0; i < picList.size(); i++) {
                    PhotoMod photoMod = picList.get(i);
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(photoMod.picurl);
                    resultList.add(localMedia);
                }
                break;
            case R.id.tv_tab3:
                onTextColor(tvTab3);
                rv_grid.setLayoutManager(staggeredGridLayoutManager);
                picList.addAll(PhotoMod.initWaterfallData());
                break;
        }
        gridAdapter.notifyDataSetChanged();
    }

    private void initTextColor(TextView... tv) {
        for (TextView textView : tv) {
            textView.setTextColor(getMColor(R.color.gray88));
        }
    }

    private void onTextColor(TextView tv) {
        initTextColor(tvTab1, tvTab2, tvTab3);
        tv.setTextColor(getMColor(R.color.maincolor));
    }
}
